package com.thinkcube.edutainment.fragment;

import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Trace;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.thinkcube.edutainment.EdutainmentConstant;
import com.thinkcube.edutainment.R;
import com.thinkcube.edutainment.ReachabilityTest;
import com.thinkcube.edutainment.adapters.CourseAdapater;
import com.thinkcube.edutainment.client.TeacherClient;
import com.thinkcube.edutainment.client.UserClient;
import com.thinkcube.edutainment.domain.OAuth;
import com.thinkcube.edutainment.domain.Teacher;
import com.thinkcube.edutainment.domain.data.CourseData;
import com.thinkcube.edutainment.domain.dto.CourseDto;
import com.thinkcube.edutainment.domain.dto.OAuthDto;

@EFragment(R.layout.teacher_profile)
public class TeacherProfile extends Fragment implements OnItemClickListener {

	@ViewById(R.id.teacher_title)
	TextView teacheTitle;

	@ViewById(R.id.other_course)
	GridView courseList;

	@ViewById(R.id.progressBar)
	ProgressBar progress;

	@ViewById(R.id.teacher_position)
	TextView position;

	@ViewById(R.id.teacher_username)
	TextView userName;

	@ViewById(R.id.teacher_email)
	TextView email;

	@ViewById(R.id.teacher_tele)
	TextView telephone;

	@ViewById(R.id.course_conduct_title)
	TextView courseConduted;

	@ViewById(R.id.teacher_profie_pic)
	ImageView prifileImage;

	private DisplayImageOptions options;
	private ImageLoader imageLoader;

	public static TeacherProfile newInstance(String string) {
		TeacherProfile fragment = new TeacherProfile_();
		Bundle bundle = new Bundle();
		bundle.putString("teacherId", string);
		fragment.setArguments(bundle);
		return fragment;
	}

	TeacherProfile() {
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.icon)
				.showImageForEmptyUri(R.drawable.icon)
				.showImageOnFail(R.drawable.icon).cacheInMemory(true)
				.cacheOnDisc(true).displayer(new SimpleBitmapDisplayer())
				.build();
		imageLoader = ImageLoader.getInstance();

	}

	@AfterViews
	void setTeacherProfile() {
		if (getArguments().containsKey("teacherId")) {

			gettoken(getArguments().getString("teacherId"));
		}
	}

	@Bean
	OAuthDto oAuthDto;

	@RestService
	UserClient userClient;

	@Trace
	@Background
	void gettoken(final String id) {
		oAuthDto.setAppId(EdutainmentConstant.APP_ID);
		oAuthDto.setAppSecret(EdutainmentConstant.APP_SCRET);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					setTokenUi(userClient.getRequestToken(oAuthDto
							.getMultiValuedMap()), id);
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});
	}

	@UiThread
	void showMessge(final String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
	}

	void setTokenUi(OAuth requestToken, String id) {

		doBackground(requestToken, id);
	}

	@Bean
	CourseDto courseDto;
	@RestService
	TeacherClient teacherClient;

	@Background
	void doBackground(OAuth requestToken, String id) {
		System.out.println("token " + requestToken.getoAuth().getToken());
		courseDto.setAuthToken(requestToken.getoAuth().getToken());
		courseDto.setUserId(id);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					doUiTecher(teacherClient.getTeacher(courseDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});

	}

	@ViewById(R.id.profile_sub_view)
	RelativeLayout profileSub;

	@ViewById(R.id.progressBar_2)
	ProgressBar progressSide;

	List<CourseData> courseListData;

	@UiThread
	void doUiTecher(Teacher teacher) {

		teacheTitle.setText(teacher.getTeacherData().getFirstName() + " "
				+ teacher.getTeacherData().getLastName());

		courseListData = teacher.getTeacherData().getCourseDataList();

		// imageLoader.displayImage(teacher.getTeacherData().get);

		courseList
				.setAdapter(new CourseAdapater(getActivity(), courseListData));

		userName.setText(teacher.getTeacherData().getUserName());

		email.setText(teacher.getTeacherData().getEmail());

		telephone.setText(teacher.getTeacherData().getMobileNo());

		imageLoader.displayImage(teacher.getTeacherData().getTeacherProfil(),
				prifileImage, options);

		profileSub.setVisibility(View.VISIBLE);

		progress.setVisibility(View.GONE);

		progressSide.setVisibility(View.GONE);

		courseConduted.setText("Courses conducted by "
				+ teacher.getTeacherData().getFirstName() + " "
				+ teacher.getTeacherData().getLastName());

		courseList.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position,
			long id) {

		final FragmentTransaction fragmentTransaction = getFragmentManager()
				.beginTransaction();
		fragmentTransaction.replace(R.id.myfragment,
				CourseViewFragment.newInstance(courseListData.get(position)),
				"newfrag");

		fragmentTransaction.addToBackStack(null);

		fragmentTransaction.commit();

	}

}
